package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;


    /**
     * 查询商铺信息
     * @param id
     * @return
     */
    public Result queryById(Long id) {
        // 解决缓存穿透
        Shop shop = cacheClient.queryWithThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById,
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 结局缓存击穿
        // 为了测试，过期时间设置为10s
        /*Shop shop = cacheClient.queryWithLogicExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById,
                10L, TimeUnit.SECONDS);*/
        if(shop == null)
            return Result.fail("商铺不存在");
        return Result.ok(shop);
    }

    /*// 查询商铺信息：解决缓存穿透版本
    private Shop queryWithThrough(Long id) {
        // 1.从redis查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopStr = stringRedisTemplate.opsForValue().get(key);
        // 2.缓存命中
        if(StrUtil.isNotBlank(shopStr)) {
            // 3.转换为Shop对象，返回给前端
            return JSONUtil.toBean(shopStr, Shop.class);
        }
        // 未命中且shopStr不为null，说明shopStr为空字符串，说明缓存穿透，则直接返回错误
        if(shopStr != null)
            return null;
        // 4.缓存未命中，查询数据库
        Shop shop = getById(id);
        // 5.商铺不存在
        if(shop == null) {
            // 写入空值到redis
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 6.商铺存在，写入到redis
        String jsonStr = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(key, jsonStr, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 7.返回给前端
        return shop;
    }*/

    /*// 查询商铺信息：互斥锁解决缓存击穿版本
    private Shop queryWithMutex(Long id) {
        // 1.从redis查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopStr = stringRedisTemplate.opsForValue().get(key);
        // 2.缓存命中
        if (StrUtil.isNotBlank(shopStr)) {
            // 3.转换为Shop对象，返回给前端
            return JSONUtil.toBean(shopStr, Shop.class);
        }
        // 未命中且shopStr不为null，说明shopStr为空字符串，说明缓存穿透，则直接返回错误
        if (shopStr != null)
            return null;
        // 4.缓存重建
        Shop shop = null;
        String lockKey = "lock:shop:" + id;
        try {
            // 4.1获取互斥锁
            boolean isLock = tryLock(lockKey);
            // 4.2判断锁是否获取成功
            if (!isLock) {
                // 4.3失败，休眠，重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 4.4成功
            // 5.再次判断缓存是否命中，即DoubleCheck
            String s = stringRedisTemplate.opsForValue().get(key);
            if(StrUtil.isNotBlank(s)) {
                // 5.1命中，无需重建缓存，返回给前端
                unLock(lockKey);  // 记得先释放锁
                return JSONUtil.toBean(s, Shop.class);
            }

            // 5.2未命中
            // 6.查询数据库
            shop = getById(id);
            // 6.1商铺不存在
            if (shop == null) {
                // 写入空值到redis
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 6.2商铺存在，写入到redis
            String jsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(key, jsonStr, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 7.释放锁
            unLock(lockKey);
        }

        // 8.返回数据给前端
        return shop;
    }*/

    /*// 查询商铺信息：逻辑过期解决缓存击穿版本
    private Shop queryWithLogicExpire(Long id) {
        // 1.从redis查询商铺缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopStr = stringRedisTemplate.opsForValue().get(key);
        // 2.判断缓存是否命中
        // 2.1未命中
        if (StrUtil.isBlank(shopStr)) {
            return null;
        }
        // 2.2命中
        // 3.判断缓存是否过期
        RedisData shopData = JSONUtil.toBean(shopStr, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) shopData.getData(), Shop.class);
        // 3.1未过期，返回商铺信息
        if(shopData.getExpireTime().isAfter(LocalDateTime.now())) {
            return shop;
        }
        // 3.2已过期
        // 4.缓存重建
        String lockKey = "lock:shop:" + id;
        // 4.1获取互斥锁
        boolean isLock = tryLock(lockKey);
        // 4.2判断锁是否获取成功
        if (!isLock) {
            // 4.3失败，返回旧的商铺信息
            return shop;
        }
        // 4.4成功
        // 5.再次判断缓存是否过期，即DoubleCheck
        String s = stringRedisTemplate.opsForValue().get(key);
        RedisData data = JSONUtil.toBean(s, RedisData.class);
        LocalDateTime expireTime = data.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())) {
            // 5.1未过期，无需重建缓存，返回给前端
            unLock(lockKey);  // 记得先释放锁
            return JSONUtil.toBean((JSONObject) data.getData(), Shop.class);
        }
        // 5.2过期
        // 6.开启独立线程，重建缓存
        try {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 7.释放锁
            unLock(lockKey);
        }
        // 8.返回旧商铺信息给前端
        return shop;
    }*/

    /*public boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);  // flag为Boolean类型，可能为null，返回值为boolean，因此可能发生空指针异常
    }

    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    // 将店铺信息保存到Redis
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        // 模拟重建缓存的耗时，注意如果jmeter测试发现所有线程的响应结果都是旧数据，到redis中看到的是新数据，说明重建是成功的
        // 只是说明sleep太久了，多个线程执行完那个负责重建的线程才重建缓存完成，减少睡眠时间就行
        Thread.sleep(50);
        // 1.构建逻辑过期时间
        RedisData shopRedisData = new RedisData();
        shopRedisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 2.查询数据库
        Shop shop = getById(id);
        shopRedisData.setData(shop);
        // 3.存入redis，无需设置过期时间，因为用的是逻辑过期时间
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shopRedisData));
    }*/

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null)
            return Result.fail("店铺id不能为空");
        // 写入数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.不需要根据距离查询
        if(x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = lambdaQuery()
                    .eq(Shop::getTypeId, typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 2.准备分页参数，注：redis的分页查询和数据库不一样，redis是limit start, end，而数据库是limit start, pageSize，即redis就是指定索引范围
        int start = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.从redis中分页查询，获取店铺id和距离
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        // GEOSEARCH key BYLONLAT x y WIDTHDISTANCE 5000 LIMIT count，可以发现LIMIT只能限制查询的数量，不能限制起始索引
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000), // 默认单位是m，返回的距离单位也是m
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if(search == null) {
            return Result.ok();
        }
        // 3.1 获取分页结果列表
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = search.getContent();
        if(content.size() <= start) {
            // 小细节，没有下一页了
            return Result.ok();
        }
        // 3.2 解析出店铺id和距离
        List<Long> ids = new ArrayList<>(content.size());  // 店铺id集合
        Map<String, Distance> distanceMap = new HashMap<>(content.size());
        // LIMIT不能限制起始索引，因此需要跳过start个元素，来实现limit start, end的分页功能
        content.stream().skip(start).forEach(result -> {
            // 3.2.1店铺id
            RedisGeoCommands.GeoLocation<String> location = result.getContent();
            ids.add(Long.valueOf(location.getName()));
            // 3.2.2距离
            Distance distance = result.getDistance();
            distanceMap.put(location.getName(), distance);
        });

        // 4.根据id查询店铺信息
        String idsStr = StrUtil.join(",", ids);
        List<Shop> shops = lambdaQuery().in(Shop::getId, ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        // 5.设置店铺的距离属性
        shops.forEach(shop -> {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        });

        return Result.ok(shops);
    }
}
